package com.ironman.compute.consumer;

import cn.hutool.core.util.StrUtil;
import com.ironman.common.params.RolParam;
import com.ironman.common.util.AccuracyUtil;
import com.ironman.event.properties.SysTrainingProperties;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.core.client.MqttClient;
import org.noear.snack.ONode;

import java.util.function.Consumer;

@Slf4j
public class RolConsumer extends BaseConsumer implements Consumer<ONode> {

    private Double preRol = null;

    private final RolParam rolParam;

    public RolConsumer(RolParam rolParam, SysTrainingProperties sysTrainingProperties, MqttClient mqttClient) {
        super(sysTrainingProperties, mqttClient);
        this.rolParam = rolParam;
    }


    @Override
    public void accept(ONode data) {
        doAccept("rol", data, (topic, dataJson, published) -> log.info("{} {} \n{}", topic, published, dataJson));
    }

    /**
     * 阈值处理
     */
    @Override
    public boolean threshold(ONode data) {
        double rol = data.select("rol").getDouble();

        if (preRol == null) {
            getCounter().incrementAndGet();
            preRol = rol;
            data.set("tt", "t");
            return true;
        }

        Integer rolThreshold = rolParam.getRolThreshold();
        double diff = Math.abs(rol - preRol);
        if (diff > rolThreshold) {
            getCounter().set(0);
            log.info("平衡触发对比阈值:{} 当前:{} 前一个:{} 相差:{} ", rolThreshold, rol, preRol, diff);
            preRol = rol;
            data.set("tt", "t");
            return true;
        }

        Integer countThreshold = rolParam.getCountThreshold();
        if (getCounter().incrementAndGet() >= countThreshold) {
            getCounter().set(0);
            log.info("平衡触发数量阈值:{} ", countThreshold);
            preRol = rol;
            data.set("tt", "c");
            return true;
        }
        return false;
    }

    @Override
    public void append(ONode data) {
        double rol = data.select("rol").getDouble();
        String sailStatus = data.select("sailStatus").getString();
        if (StrUtil.isBlank(sailStatus)) {
            return;
        }
        String posture;
        if (Math.abs(rol) <= rolParam.getRolDecisionThreshold()) {
            posture = "平衡";
        } else {
            if ("U_S".equals(sailStatus) || "D_S".equals(sailStatus)) {
                if (rol > 0) {
                    posture = "倾斜";
                } else {
                    posture = "反扣";
                }
            } else {
                if (rol > 0) {
                    posture = "反扣";
                } else {
                    posture = "倾斜";
                }
            }
        }
        data.set("posture", posture);
    }

    @Override
    public void precision(ONode data) {
        double rol = data.select("rol").getDouble();
        data.set("rol", AccuracyUtil.downDirectionInteger(rol));
    }
}
